/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', 'N/runtime'], function (search, record, runtime) {
        function getInputData() {
            var mySearch = initSearch();
            var alls = [];
            var results = mySearch.run().getRange(0, 1000);
            var j = 1;
            while (results.length > 0 && j < 2) {
                for (var i = 0; i < results.length; i++) {
                    var result = results[i];
                    var tmp = {};
                    tmp.id = result.id;
                    alls[alls.length] = tmp;
                }
                results = mySearch.run().getRange(j * 1000, 1000 + j * 1000);
                j++;
            }
            log.debug('alls', JSON.stringify(alls));
            return alls;
        }

        function map(context) {
            var txId = JSON.parse(context.value).id;
            var txRecord = record.load({type: 'customrecord_fba_transaction_report', id: txId, isDynamic: true});
            var tx = {};
            tx.id = txId;
            tx.sku = txRecord.getValue('custrecord_tran_sku');
            tx.orderId = txRecord.getValue('custrecord_tran_order_id');
            tx.quantity = txRecord.getValue('custrecord_tran_quantity');

            tx.datetime = txRecord.getValue('custrecord_tran_datetime');
            tx.settlementId = txRecord.getValue('custrecord_tran_settlement_id');
            tx.description = txRecord.getValue('custrecord_tran_description');
            tx.type = txRecord.getValue('custrecord_tran_type');
            tx.storeId = txRecord.getValue('custrecord_tran_store_information');

            tx.country = txRecord.getValue('custrecord_tran_country');
            tx.country_name = txRecord.getText('custrecord_tran_country');
            tx.currency = txRecord.getText('custrecord_tran_currency');
            log.debug('tx.type' + '  ' + tx.type, JSON.stringify(tx));

            try {
                var fieldLookUp1 = search.lookupFields({
                    type: 'customrecord_platform_store_information',
                    id: tx.storeId,
                    columns: ['custrecord_store_location']
                });
                var locationId = fieldLookUp1.custrecord_store_location[0].value;

                log.debug('locationId', locationId);

                var location = record.load({type: 'location', id: locationId});

                var subsidiaryId = location.getValue('subsidiary');
                log.debug('subsidiaryId', subsidiaryId);

                // var fieldLookUp2 = search.lookupFields({
                //     type: 'location',
                //     id: tx.storeId,
                //     columns: ['subsidiary']
                // });
                // log.debug('fieldLookUp2', fieldLookUp2);
                // var subsidiaryId = fieldLookUp1.subsidiary;


                var adjustAccount = 232; //1901.01 待处理财产损溢:待处理流动资产损溢
                var adjustId;
                if (tx.country_name === "加拿大" || tx.country_name === "Canada") {
                    if (tx.description === "FBA Inventory Reimbursement - Customer Return" ||
                        tx.description === "FBA Inventory Reimbursement - Customer Service Issue" ||
                        tx.description === "FBA Inventory Reimbursement - Damaged:Warehouse" ||
                        tx.description === "FBA Inventory Reimbursement - General Adjustment" ||
                        tx.description === "FBA Inventory Reimbursement - Lost:Warehouse") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "美国" || tx.country_name === "United States") {
                    if (tx.description === "FBA Inventory Reimbursement - Customer Return" ||
                        tx.description === "FBA Inventory Reimbursement - Customer Service Issue" ||
                        tx.description === "FBA Inventory Reimbursement - Damaged:Warehouse" ||
                        tx.description === "FBA Inventory Reimbursement - General Adjustment" ||
                        tx.description === "FBA Inventory Reimbursement - Lost:Warehouse") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "英国" || tx.country_name === "United Kingdom") {
                    if (tx.description === "FBA Inventory Reimbursement - Customer Return" ||
                        tx.description === "FBA Inventory Reimbursement - Damaged:Warehouse" ||
                        tx.description === "FBA Inventory Reimbursement - General Adjustment") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "德国" || tx.country_name === "Germany") {
                    if (tx.description === "Versand durch Amazon Erstattung für Lagerbestand -  Allgemeine Anpassung" ||
                        tx.description === "Versand durch Amazon Erstattung für Lagerbestand - Im Lager beschädigt" ||
                        tx.description === "Versand durch Amazon Erstattung für Lagerbestand - Kundenrücksendung") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "法国" || tx.country_name === "France") {
                    if (tx.description === "Remboursement Stock Expédié par Amazon - Ajustement général" ||
                        tx.description === "Remboursement Stock Expédié par Amazon - Endommagé:entrepôt" ||
                        tx.description === "Remboursement Stock Expédié par Amazon - Perdu:sortant" ||
                        tx.description === "Remboursement Stock Expédié par Amazon - Retour Client") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "西班牙" || tx.country_name === "Spain") {
                    if (tx.description === "FBA Inventory Reimbursement - Customer Return" ||
                        tx.description === "Reembolso de inventario - ajuste general" ||
                        tx.description === "Reembolso de inventario - extraviado en el almacén") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "意大利" || tx.country_name === "Italy") {
                    if (tx.description === "Rimborso inventario Logistica di Amazon. Aggiustamento generale" ||
                        tx.description === "Rimborso inventario Logistica di Amazon. Danneggiato in magazzino" ||
                        tx.description === "Rimborso inventario Logistica di Amazon. Reso cliente") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }

                if (tx.country_name === "日本" || tx.country_name === "Japan") {
                    if (tx.description === "退还亚马逊物流库存-损失：履行中心：" ||
                        tx.description === "亚马逊物流库存的退款-买方退货：") {

                        adjustId = createAdjust(tx, adjustAccount, locationId, subsidiaryId);
                    }
                }


            } catch (e) {
                // record.submitFields({
                //     type: 'customrecord_fba_transaction_report',
                //     id: tx.id,
                //     values: {
                //         custrecord_tran_journal_flag: true,
                //         custrecord_tran_journal_message: JSON.stringify(e)
                //     }
                // });
                log.error('error', JSON.stringify(e));
            }
        }

        function createAdjust(tx, adjustAccount, locationId, subsidiaryId) {
            var rec = record.create({type: 'inventoryadjustment', isDynamic: true});

            rec.setValue('customform', 137);
            rec.setValue('subsidiary', subsidiaryId);
            rec.setValue('account', adjustAccount);
            rec.setValue('adjlocation', locationId);
            rec.setValue('custbody_amzn_tx_typ', tx.type);
            rec.setValue('custbody_amzn_stl_id', tx.settlementId);
            rec.setValue('custbody_amzn_ord_id', tx.orderId);
            rec.setValue('custbody_amzn_tx_desc', tx.description);
            rec.setValue('custbody_amzn_tx', tx.id);

            rec.selectNewLine('inventory');
            try {
                rec.setCurrentSublistValue('inventory', 'item', tx.sku);
            } catch (e) {
                rec.setCurrentSublistText('inventory', 'item', 'AECS040900025');
            }
            rec.setCurrentSublistValue('inventory', 'adjustqtyby', tx.quantity);
            rec.setCurrentSublistValue('inventory', 'location', locationId);

            rec.commitLine('inventory');


            var recId = rec.save();
            return recId;
        }


        function reduce(context) {
        }

        function summarize(summary) {
        }

        function initSearch() {
            var mySearch = search.create({
                type: 'customrecord_fba_transaction_report',
                filters: [['custrecord_tran_type', 'is', 'Adjustment'],
                    'or', ['custrecord_tran_type', 'is', 'Anpassung'],
                    'or', ['custrecord_tran_type', 'is', 'Ajustement'],
                    'or', ['custrecord_tran_type', 'is', 'Ajuste'],
                    'or', ['custrecord_tran_type', 'is', 'Modifica'],
                    'or', ['custrecord_tran_type', 'is', '調整']]
            });
            return mySearch;
        }


        return {
            getInputData: getInputData,
            map: map,
            reduce: reduce,
            summarize: summarize
        };
    }
);